package com.lst.servlet;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.JPushEnum;
import com.lst.common.JPushMessage;
import com.lst.entity.request.FocusReqPara;
import com.lst.model.Focus;
import com.lst.model.MstClient;
import com.lst.model.MstMessage;
import com.lst.service.FocusService;
import com.lst.service.MstClientService;
import com.lst.service.MstMessageService;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: FocusAddServlet
 * @Description: 关注添加接口
 * 
 */
public class FocusAddServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private FocusService focusService = ctx.getBean(FocusService.class);
	
	private MstClientService mstClientService = ctx.getBean(MstClientService.class);
	
	private MstMessageService mstMessageService = ctx.getBean(MstMessageService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		BaseResponse resPara = new BaseResponse();

		try {
			FocusReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			int userid = Integer.parseInt(reqPara.getUserid());
			int focusUser = Integer.parseInt(reqPara.getFocusUserId());
			
			Map<String, Object> reqMap = new HashMap<String, Object>();
			reqMap.put("focusUser", focusUser);
			reqMap.put("createUser", userid);

			Focus focus=focusService.selectByMap2(reqMap);
			if(focus==null){
				Focus md = new Focus();	
				md.setCreateUser(userid);
		        md.setFocusUser(focusUser);
				md.setCreateDate(startDate);
				md.setIsDelete(false);
				focusService.insert(md);
				
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}else{
				focusService.updateFocus2(reqMap);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}
			
			//关注发通知
			if(userid!=focusUser){
					MstClient mstClient = mstClientService.selectByPrimaryKey(userid);
					if (mstClient != null) {
						String name = mstClient.getNickname();

						MstMessage message = new MstMessage();
						message.setReceiveid(focusUser);
						message.setReceivetype(CommCode.SYSCODE_MSG_TYPE_RECEIVE_CLIENT);
						message.setSendid(Integer.valueOf(userid));
						message.setSendtype(CommCode.SYSCODE_MSG_TYPE_SEND_CLIENT);
						message.setContent("关注了你！");
						message.setEnabled(true);
						message.setIsdeleted(false);
						message.setCreateuser(-1);
						message.setCreatedate(startDate);
						message.setReserved2(CommCode.SYSTEM_CARESEL_RANGE_Focus);
						message.setReserved7(false);
						message.setType(CommCode.SYSCODE_MSG_TYPE_PUSH);
						mstMessageService.insert(message);
						 message.setReserved12(name);
						JPushMessage.pushMessage(message, JPushEnum.ALL_ALIAS);
					}
			}
			
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
	//		logger.info("FocusAddServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

//			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public FocusReqPara getReqPara(HttpServletRequest request) {

		FocusReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new FocusReqPara());

			reqPara = (FocusReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String focusUserId = request.getParameter("focusUserId");
	
//			logger.info("reqPara userid:" + userid);
//			logger.info("reqPara focusUserId: " + focusUserId);

	        reqPara.setUserid(userid);
	        reqPara.setFocusUserId(focusUserId);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		FocusReqPara cdReqPara = (FocusReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

	 if (StringUtils.isEmpty(cdReqPara.getFocusUserId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("被关注者id为空");
		} else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}

		return  flag;
	}

}
